﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using DAL;
using DTO;
using System.Configuration;
using System.Security.Principal;
using System.IO;
using System.Security.AccessControl;

namespace BLL
{
    public class Administrators
    {
        GetData data = new GetData();
        UpdateData up = new UpdateData();
        #region User_Management
        public List<UserEntity> GetAllUser()
        {
            return data.GetAllUser();
        }
        public void InsertUser(UserEntity user)
        {
            user.Password = CryptorEngine.Encrypt(user.Password, true);
            up.InsertUser(user);
        }

        public List<PermissionEntity> LoadListPermission()
        {
            return data.LoadListPermission();
        }

        public List<PermissionEntity> LoadListPerEachUser(int userid)
        {
            var UserPermit = data.LoadPermitDetail(userid);
            var PermitList = data.LoadListPermission();

            foreach (var permit in UserPermit)
            {
                foreach (var permitrow in PermitList)
                {
                    if (permit.Permission_ID == permitrow.Permission_ID)
                    {
                        permitrow.Status = permit.Status;
                    }
                }
            }
            return PermitList;
        }

        public void UpdateUserPermit(PermissionEntity permit, int userid)
        {
            
            up.UpdateUserPermit(permit, userid);
        }
        #endregion        


        #region Catalog_Collector
        public List<CollectorEntity> LoadListCollector()
        {
            return data.LoadListCollector();
        }
        
        public void AddNewCollector(string Collector_ID, string FullName, int Region_ID)
        {
            up.AddNewCollector(Collector_ID, FullName, Region_ID);
        }

        public void UpdateCollector(CollectorEntity collector)
        {
            up.UpdateCollector(collector);
        }

        public CollectorEntity LoadCollector(int Collector_ID)
        {
            return data.LoadCollector(Collector_ID);
        }
        #endregion

        public void AddNewRegion(RegionEntity re)
        {
            RegionService sv = new RegionService();
            sv.AddNewRegion(re);
        }

        public void SaveConfig(Dictionary<string, string> con , ref string message)
        {
            string configPath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
            if (WriteAccess(configPath))
            {
                System.Configuration.Configuration config =
             ConfigurationManager.OpenExeConfiguration
                        (System.Windows.Forms.Application.ExecutablePath);

                foreach (var item in con)
                {
                    config.AppSettings.Settings[item.Key].Value = item.Value;
                }

                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
                message = "Thiết lập thành công.";
            }
            else
            {
                message = "Thiết lập thất bại.\n" + "Hãy chắc chắn rằng bạn có phân quyền Administrator cho phép thiết lập trên máy này.";
            }
            
        }

        public static bool WriteAccess(string fileName)
        {
            if ((File.GetAttributes(fileName) & FileAttributes.ReadOnly) != 0)
                return false;

            // Get the access rules of the specified files (user groups and user names that have access to the file)
            var rules = File.GetAccessControl(fileName).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));

            // Get the identity of the current user and the groups that the user is in.
            var groups = WindowsIdentity.GetCurrent().Groups;
            string sidCurrentUser = WindowsIdentity.GetCurrent().User.Value;

            // Check if writing to the file is explicitly denied for this user or a group the user is in.
            if (rules.OfType<FileSystemAccessRule>().Any(r => (groups.Contains(r.IdentityReference) || r.IdentityReference.Value == sidCurrentUser) && r.AccessControlType == AccessControlType.Deny && (r.FileSystemRights & FileSystemRights.WriteData) == FileSystemRights.WriteData))
                return false;

            // Check if writing is allowed
            return rules.OfType<FileSystemAccessRule>().Any(r => (groups.Contains(r.IdentityReference) || r.IdentityReference.Value == sidCurrentUser) && r.AccessControlType == AccessControlType.Allow && (r.FileSystemRights & FileSystemRights.WriteData) == FileSystemRights.WriteData);
        }


    }
}
